package cn.shuangze.assetsms.view;

import cn.shuangze.assetsms.component.MyJTable;
import cn.shuangze.assetsms.dao.AssetsInfoDao;
import cn.shuangze.assetsms.dao.impl.AssetsInfoDaoJDBCImpl;
import cn.shuangze.assetsms.dao.test.OptionType;
import cn.shuangze.assetsms.entity.AssetsInfo;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class ShowAssetsInfo extends JDialog implements ActionListener {

    //定义DAO
    private AssetsInfoDao assetsInfoDao;

    private OptionType flag;
    private Thread showThread;
    private AssetsInfo assetsInfo;

    //框架的大小
    private Dimension viewSize = new Dimension(600, 300);
    private Font font = new Font("Dialog", 0, 12);

    //定义所用的面板
    private JPanel southPanel = new JPanel();
    private JPanel centerPanel = new JPanel();

    //定义图形界面元素
    private JLabel[] jLabel = new JLabel[4];
    private JTextField[] jTextField = new JTextField[4];
    JButton selectBtn = new JButton("查询", new ImageIcon("images\\search.png"));

    //定义表格
    private JTable jTable;
    private DefaultTableModel tableModel;


    public ShowAssetsInfo(OptionType flag) {

        this.flag = flag;
        assetsInfoDao = new AssetsInfoDaoJDBCImpl();

        showThread = new Thread(() -> {
            try {
                showTableData();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "窗口初始化错误，错误原因：" + e.getMessage(),
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        //界面初始化
        init();
    }


    private void init() {
        Container contentPane = this.getContentPane();
        contentPane.setLayout(new BorderLayout());

        this.setModal(true);
        this.setSize(viewSize);
        this.setResizable(true);

        //设置标题
        this.setTitle("资产信息查询");

        //设置运行时窗口的位置
        this.setLocationRelativeTo(null);

        //表格布局
        tableModel = new DefaultTableModel();  // 创建默认表格模式
        jTable = new MyJTable(tableModel);  // 创建表格 禁用编辑功能
        ListSelectionModel listSelectionModel = jTable.getSelectionModel();
        listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  // 设置表格选择模式为单一选择
        JScrollPane jScrollPane1 = new JScrollPane(jTable);  // 创建一个滚动面板，包含表格
        jScrollPane1.setPreferredSize(viewSize);  //设置滚动面板大小
        DefaultTableCellRenderer cr = new DefaultTableCellRenderer();
        cr.setHorizontalAlignment(JLabel.CENTER);  //表格内容居中
        jTable.setDefaultRenderer(Object.class, cr);

        showThread.start();

        contentPane.add(jScrollPane1, BorderLayout.NORTH);

        if (flag == OptionType.SELECT_ID) {

            JPanel line1 = new JPanel();
            JPanel line2 = new JPanel();
            for (int i = 0; i < jLabel.length; i++) {

                jLabel[i] = new JLabel();
                jLabel[i].setFont(font);

                jTextField[i] = new JTextField();
                jTextField[i].setColumns(12);

                if (i < jLabel.length / 2) {
                    line1.add(jLabel[i]);
                    line1.add(jTextField[i]);
                } else {
                    line2.add(jLabel[i]);
                    line2.add(jTextField[i]);
                }

            }
            jLabel[0].setText("编号ID");
            jLabel[1].setText("名称");
            jLabel[2].setText("类型ID");
            jLabel[3].setText("型号");

            centerPanel.setLayout(new GridLayout(2, 1));
            centerPanel.add(line1);
            centerPanel.add(line2);
            contentPane.add(centerPanel, BorderLayout.CENTER);

            southPanel.add(selectBtn);
            contentPane.add(southPanel, BorderLayout.SOUTH);

            selectBtn.addActionListener(this);
            jTextField[0].addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent e) {
                    char keyChar = e.getKeyChar();
                    if (!(keyChar >= '0' && keyChar <= '9')) {
                        e.consume();
                    }
                }
            });

            jTextField[2].addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent e) {
                    char keyChar = e.getKeyChar();
                    if (!(keyChar >= '0' && keyChar <= '9')) {
                        e.consume();
                    }
                }
            });

        }
    }


    private void showTableData() throws Exception {
        String[][] colValue = null;
        if (flag == OptionType.SELECT_ALL) {
            colValue = assetsInfoDao.findAll();

        } else if (flag == OptionType.SELECT_ID) {
            colValue = assetsInfoDao.findByCondition(assetsInfo);
        }

        String[] colName = {"资产编号", "资产名称", "所属类型", "型号", "价格", "购买日期", "状态", "备注"};
        tableModel.setDataVector(colValue, colName);
        jTable.revalidate();  //刷新表格
    }


    @Override
    public void actionPerformed(ActionEvent e) {
        Object obj = e.getSource();

        if (obj == selectBtn) {

            try {
                int assetsId = 0;
                int typeId = 0;

                if (!jTextField[0].getText().equals("")) {
                    assetsId = Integer.parseInt(jTextField[0].getText().trim());
                }

                if (!jTextField[2].getText().equals("")) {
                    typeId = Integer.parseInt(jTextField[2].getText().trim());
                }

                String name = jTextField[1].getText().trim();
                String model = jTextField[3].getText().trim();

                assetsInfo = new AssetsInfo(assetsId, name, typeId, model, null, null, null, null);

                showTableData();

            } catch (NumberFormatException e1) {

                JOptionPane.showMessageDialog(this, "ID输入的不是数字，请重新输入！",
                        "消息", JOptionPane.ERROR_MESSAGE);

            } catch (Exception e2) {

                JOptionPane.showMessageDialog(this, "查询失败，错误原因：" + e2.getMessage(),
                        "错误", JOptionPane.ERROR_MESSAGE);

            }
        }
    }

}
